% (c) GreenSocs Ltd
% author: Christian Schroeder <schroeder@eis.cs.tu-bs.de>

\cleardoublepage

\chapter{GreenControl}
\label{GreenControl}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Overview}

See figure \ref{fig:GreenControlImpl} to get an overview of the \GreenControl classes and how they are connected.

\begin{figure}%[H]%[htbp]
	\centerline{
	\includegraphics[width=\textwidth]{GreenControlImpl3.eps}
	} 
	\caption{This image shows how the GreenControl implementation is realized. }
	\label{fig:GreenControlImpl}
\end{figure}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Namespace gs::ctr and naming conventions}
\label{GreenControlNamespaceAndConventions}
This framework is placed inside the namespace {\sffamily gs::ctr} which is a sub namespace of the GreenSocs namespace {\sffamily gs}. All \GreenControl classes are placed in this namespace.

%\Note{Compatibility Note}{Namespace compativility to release 0.2}{
%	To be compatible to the old namespaces (tlm::gc, tlm::gc::config) the header
%	file \Datei{greencontrol/namespace\_compatibility.h} can be included!
%}

For the correct namespace of the classes used in this document please
refer to the doxygen generated API reference.

The classes that are visible to the user have the prefix \lstinline|gc| or \lstinline|GC|.

The \GreenControl framework, and this  documentation make use of some abbreviations:
\begin{itemize}
	\item \emph{GC} means \emph{GreenControl},
\end{itemize}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Files}
\label{GreenControlFiles}
The GreenSocs package \emph{greencontrol} contains the framework files.

The framework is organized in subdirectories:
\begin{itemize}

  \item \Verzeichnis{greencontrol}:\newline
  	Main user include files for the Core and services.

  \item \Verzeichnis{greencontrol/core}:\newline
  	\GreenControl Core with all classes needed by the user to create the core and needed by the plugins and APIs for connection.

  \item \Verzeichnis{greencontrol/\textless servicename\textgreater}: \newline
  	For each service which can be added to the framework, a subdirectory is created which contains 
    \begin{itemize}
      \item \Verzeichnis{plugin}: a plugin directory and 
      \item \Verzeichnis{apis}: an API's directory
    \end{itemize}
    Each service should provide a single include header file in the \Verzeichnis{greencontrol} folder. The file should include the basic classes needed for the service.

  \item \Verzeichnis{greencontrol/docs/\textless servicename\textgreater}: \newline
  	Documentation directory with one subdirectory for each service.

  \item \Verzeichnis{greencontrol/examples}: \newline
  	Examples

\end{itemize}

%\noindent
%\begin{minipage}{\textwidth}
%\begin{tabularx}{\textwidth}{|l|X|}
%	\cline{1-1}\cline{2-2}\multicolumn{2}{|l|}{ {\bf greencontrol}    }\\ 
%	\cline{1-1}\cline{2-2} core.h    &  The include file for the user. \\ 
%	\cline{1-1}\cline{2-2}\multicolumn{2}{|l|}{  {\bf greencontrol/core}    }\\ 
%	\cline{1-1}\cline{2-2} controladdressmap.h    &  Used by the Core: class \lstinline|ControlAddressMap| to provide a map for address resolution (name to port number in multi port).   \\ 
%	\cline{1-1}\cline{2-2} controlports.h    &  Ports to transport transaction containers: \mbox{\lstinline|control_target_port|,} \mbox{\lstinline|control_target_multi_port|,} \mbox{\lstinline|control_initiator_port|}, \mbox{\lstinline|control_initiator_multi_port|.}   \\ 
%	\cline{1-1}\cline{2-2} gc\_core.h    &  \GreenControl Core which routes the ControlTransactionContainer to the target. Main file which has to be included by the top level (testbench). \\ 
%	\cline{1-1}\cline{2-2} gc\_globals.h    &  Global settings for \GreenControl, needed by all other header files. \\ 
%	\cline{1-1}\cline{2-2} gc\_port\_if.h    &  Interface with the virtual methods \lstinline|masterAccess(ControlTransactionContainer\&)| and \lstinline|slaveAccess(ControlTransactionContainer\&)|. Must be implemented by APIs which want to use the gc\_port. These methods are called when a transaction arrives at the initiator or target port.   \\ 
%	\cline{1-1}\cline{2-2} gc\_port.h    &  The class \lstinline|gc_port| is the port to the \GreenControl Core. It has a sc\_port \lstinline|api_port| which has to be bound by the API (either \lstinline|GCnf_Api| or a User API) to serve incoming transactions. Outgoing transactions can be sent with notify(transaction) in its target and master ports.   \\ 
%	\cline{1-1}\cline{2-2} gc\_transaction.h    &  Holds the transaction container and the phases; classes/typedefs: \lstinline|ControlTransaction|, \lstinline|ControlTransactionHandle|, \lstinline|ControlPhase|,  \lstinline|ControlPhaseHandle|, \lstinline|ControlTransactionContainer|   \\ % TODO: remove phases?
%	\cline{1-1}\cline{2-2} gcexception.h    &  \GreenControl-wide exception base class with special derived exception classes (e.g. command line parser exception).   \\ 
%	\cline{1-1}\cline{2-2} gcnf\_api\_if.h    &  Interface \lstinline|gcnf_api_if|: Allows the \GreenControl Core to control the initialize-mode for initial configuration.   \\ 
%	\cline{1-1}\cline{2-2} gscontrol.h    &  Information file. Not to be included.  \\ 
%	\cline{1-1}\cline{2-2} helpfunctions.h    &  Some helping functions which are used by various classes.  \\ 
%	\hline
%\end{tabularx}
%\end{minipage}

%\vspace{1 cm}

%\noindent
%\begin{minipage}{\textwidth}
%\begin{tabularx}{\textwidth}{|l|X|}
%	\cline{1-1}\cline{2-2}\multicolumn{2}{|l|}{  {\bf greencontrol/core/transport}    }\\ 
%	\cline{1-1}\cline{2-2} *    &  These files represent the communication structure which is based on the \GreenBus project using TLM-2.0 concepts (not the OSCI TLM-2.0 implementation!).  \\ 
%	\hline
%\end{tabularx}
%\end{minipage}

%\vspace{1 cm}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Communication}

%The \GreenControl Core originally is based on \GreenBus and adopts its concepts. To allow even greater performance and maintainability than \GreenBus some well-chosen elements have been copied to the \GreenControl framework (directory \Verzeichnis{greencontrol/core/transport}). This also removes the dependence on the \GreenBus package and allows GreenControl and its plugins being used within the \GreenBus core.
The \GreenControl communication mechanism uses a methodology similar to TLM, formally it was based on \GreenBus. It is important to notice that although the TLM concept of single transport calls transfering an extendible transaction container is used, no SystemC or OSCI TLM code is used, to avoid the \GreenControl mechansim from being visible in SystemC analysis tools.

\subsection{Port binding}
\label{commPortBinding}
\begin{itemize}
	%\item All APIs and API adapters get their ports \lstinline|control_initiator_port| and \lstinline|control_target_port| automatically by using (instantiating) \lstinline|gc_port|. 

	%\item As a result of this instantiation the Core can identify these APIs and its ports when going through the object hierarchy. The Core can bind the ports automatically to the multi ports of the Core. This automatically binding is done either by the Core during before\_end\_of\_elaboration or by each \lstinline|gc_port| after port construction for immediate binding (call of \lstinline|process_ports()|). \newline The Core goes through the sim context hierarchy and searches for instances of the \lstinline|control_xx_port|s and saves pointers to them into a list (if not yet in it). Afterwards these ports are automatically bound to the multi ports of the Core (if not yet done). Hence the user need not bind the ports themselves. 
	
	%\item The Core can identify already bounded ports with the call \lstinline|is_Bound()|, so it is does not bind ports	twice, e.g. if each port does immediate binding.
	
	\item An API or Plugin automatically connects to the Core just by instantiating a \lstinline|gc_port|, which automatically performs the connection.
	
	\item The constructors of the control ports ask for special information: 
	\begin{itemize}
		\item APIs and plugins have to specify their supported control service. 
		\item Plugins have to set a bool to true to show that a plugin is connected to serve all transactions to its supported service. 
		\item APIs and plugins have to specify their target address (type \lstinline|cport_address_type|) which is a \lstinline|gc_port_if| pointer and has to be set to their pointer address. 
		\item APIs and plugins submit a human readable unique name which is used for debug and maybe future use. 
		\item These variables are read by the Core when building the address map (see section \ref{commAddressing}). 
	\end{itemize}

\end{itemize}


\subsection{Addressing}
\label{commAddressing}
The \GreenControl Core routes the transaction containers with the two fields "Service" and "Target". The target field is the address (target's \lstinline|gc_port_if| pointer address) of the API or plugin where the transaction should be delivered. The service field specifies the service which is used for categorization (for analyzing the communication) and is used for routing:  

If the sender does not know the correct address of the plugin which is responsible for the service (normal case!), the sender may leave the target field blank (\lstinline|0|) and only set the service field. The router knows which plugin belongs to which service (because of the constructor parameters of the ports, see section \ref{commPortBinding}) and routes the transaction to the (only) plugin supporting that service. 

The plugin has to know the address of the API it wants to reach. That is no problem because each API first sends a transaction to the plugin (e.g. parameter add, set or observer registration) and the plugin stores the MasterID (which can be found in the transaction container) as target address for that API/module). 

The target address allows a user module to use multiple (different) APIs for one service (e.g. it uses scml parameters and GCnf parameters).  



\subsection{Port usage in the APIs}
This is about how to use the ports inside an implementation of an User API adapter. 

The interface \lstinline|gcnf_api_if| waits for the method: 

\begin{itemize}
\item \lstinline[language=TeX]|void transport(ControlTransactionHandle& tr)|
\end{itemize}

This method is called by the sending initiator.


%\begin{landscape}
\begin{table}[htbp] 
\begin{center}
\begin{sideways}
\begin{tabularx}{23cm}{|p{2.3cm}|p{2.4cm}|p{3cm}|X|X|X|}
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\em Field name}     &  {\em Member name}    &  {\em Data type}    &  {\em Example 1}    &  {\em Example 2}    &  {\em Explanation}   \\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf Service}}      &  mService           &  ControlService (enum)    &  \lstinline|CONFIG_SERVICE|    &     &  Service specification; used for routing to the correct plugin and analysis  \\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf Target}}, \mbox{\bf {\textsf Address}}     &  mTarget    &  cport\_address\_type (void*)    &  \lstinline|3215719780|    &  \lstinline|3215759780|    &  Routing target (address of API or plugin) where the Core should route the transaction to   \\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf Command}}      &  mCmd    &  unsigned int (for specialized enumerations)    &  \lstinline|CMD_SET_PARAM|    &  \lstinline|CMD_GET_PARAM_LIST|    &  Command the target should execute, available commands are dependent on the service. \\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf AnyUint}}      &  mAnyUint    &  unsigned int  &    &    & Field for any type of unsigned int information. \\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf Specifier}}    &  mSpecifier    &  ControlSpecifier (string)    &  \lstinline|jpeg.compressionParam1|    &  \lstinline|mymodule.submodule.param2|    &  The affected object; different concerning to the command   \\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf Value}}        &  mValue    &  ControlValue (string)    &  \lstinline|"42"|    &  \lstinline|"myTestValue"|    &  Value; different concerning to the command   \\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf MasterID}}     &  mID    &  cport\_address\_type (void*)    &  \lstinline|3213638188|    &     &  Address of the sender API or plugin. Automatically set by port.   \\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf Error}}        &  mError    &  unsigned int    &  \lstinline|0|    &  \lstinline|1|    &  Error code for response (0=no error)   \\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf LogPointer}}      &  mLogPointer    &  log\_if*  &    &    & Field for any type of pointer, with logger information.\\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf AnyPointer}}      &  mAnyPointer    &  void*  &    &    & Field for any type of pointer, initiator and target must know the type and do casts. Better use LogPointer if possible!\\ 
	\cline{1-1}\cline{2-2}\cline{3-3}\cline{4-4}\cline{5-5}\cline{6-6} {\bf {\textsf AnyPointer2}}      &  mAnyPointer2    &  void*  &    &    & Another field for any type of pointer. Better use LogPointer if possible! \\ 
	\hline
\end{tabularx}
\end{sideways}
\end{center}
\caption{Fields of the Transaction Container. }
\label{tbl:TransactionContainer}
\end{table}
%\end{landscape}

\subsection{Transaction Container}

The transaction container consists of various fields (see table \ref{tbl:TransactionContainer} on page \pageref{tbl:TransactionContainer}).

The command field is kept general as an unsigned integer. Since the
transaction object \lstinline|ControlTransaction| could be used by
various services this field is dependent on the  specific service
being used. The APIs and plugins should use an enumeration which is specialized for their service.

Not all fields are necessarily used by each service. Since we have a pool of existing transaction objects and not all fields are reseted each time being reused there is no performance issue having more fields than needed.

The sender of a transaction {\em must ensure} that {\em all} fields that are processed by the receiver are set or reseted because transactions are taken out of the pool and may contain not reseted fields! The only fields that are reseted by default are the \textsf{Error} field and the \textsf{Service} field. 

See \GreenConfig User's Guide for the available commands for the configuration service and how to add new commands for that service.

\subsection{Transaction Extensions}
\label{sec:TransactionExtensions}

The transaction class provides an extension mechanism. This mechanism is similar to the TLM-2.0 extensions.

There is a base class \lstinline|gc_transaction_extension| to derive user extensions from to store and transport them in the transaction. Derive your transaction extension class in the following way:\newline
\begin{lstlisting}[language=TeX]
class my_extension 
  : public gs::ctr::gc_transaction_extension<my_extension> 
  , public gs::ctr::log_if
\end{lstlisting}
The base class \lstinline |log_if| is optional but recommended to allow logging with the GC\_Logger!

Extensions can be added to a ControlTransaction (one of each extension type), similar to TLM-2.0-extensions
but not using memory management.
Extension can only cleared (not released) because the owner shall care about the extension's
 memory management - which is not hard because a \lstinline|ControlTransaction| shall not be assumed to live longer than just during the transport call (this is different from TLM-2.0).

 No \lstinline|ControlTransaction| should be created before static initialization ended, because the 
 maximum number of extensions may not be known yet before! If a transaction is created
 during static initialization, its extensions vector must be resized to \lstinline|max_num_gc_transaction_extensions()|.
 
Typically it is not necessary to copy transactions. When copying transactions, no deep copy of pointers and extension is made!

\WarningSymbol{Note:} There are two different extension types: Transaction Extensions (these ones) and Service Extensions (see section \ref{GCNewServices})!

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Order for constructing GreenControl elements}
\label{OrderConstructionElements}
The \GreenControl framework requires the a strict constructing order. It is recommended to instantiate the elements manually observe the following rules. Alternatively the automatic mechanism described afterwards can be used if there is no way to ensure that the \GreenControl elements are instantiated before any code accessing the services, e.g. in a tool environment.

\begin{itemize}

  \item Before any other \GreenControl elements may be instantiated or used, the singleton \emph{Core} is needed.
\begin{lstlisting}
gs::ctr::GC_Core   core;
\end{lstlisting}
Alternatively use the following static function call which will create (at first call) and return the singleton (each call):
\begin{lstlisting}
gs::ctr::GC_Core::get_instance();
\end{lstlisting}

  \item Afterwards other \GreenControl elements may be instantiated, beginning with the plugins. For example the Configuration Service within the namespace \lstinline|gs::cnf| is the next one to instantiate:
\begin{lstlisting}
gs::cnf::ConfigPlugin   configPlugin(database);
\end{lstlisting}
See the related documentation for the recommended and possible ways of creating the service plugins.

  \item The plugin instantiations may be followed by any User APIs and modules (containing User APIs). 
\end{itemize}

The construction order for plugins, APIs and modules is not fixed. Depending on the application different orders may be useful. In general it will be reasonable to instantiate all plugins prior to modules which make use of them. If a user module tries to make use of a not existing service plugin during its construction the routing of the transaction will fail and result in a routing error.

\subsection{Alternative automatic construction}
Alternatively to the manual Core instantiation, you can rely on its automatic creation. During the first creation of a \lstinline|gc_port| the Core will be created by the static get instance function being called by the port constructor. Typically this should be the case when creating the first service plugin, e.g. the configuration plugin.

See the related documentation for possible automatic instantiations of the plugins.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Command line options/switches}
Some API Tools may need to parse command line options and switches, e.g. config file parser to get the filename (see \GreenConfig documentation), config command line parser to get parameter values etc.

To get a variable framework where these APIs and tools can be added and removed very easily we have to use a general approach for parsing the command line: 

To achieve highly modularity each API tool, which needs to parse the command line, gets the whole command line arguments like they are submitted to the \lstinline|main| method. The parser then only processes the options and switches which are supported by that parser and ignores the other ones. The parsers must not change the \lstinline|argc| value and the \lstinline|argv| array because all parser should get the original values. The parser should work on a copy of the argument array: if e.g. the command \lstinline|getopt| or \lstinline|getopt_long| is used, a copy of \lstinline|argv| has to be used because these methods change the arrays during processing. 

\begin{itemize}
	\item It is essential to {\em make sure that each option or switch is used only once in the entire framework}. 

	\item The parsers may make use of (and throw or throw and catch) the exception class \lstinline|CommandLineException|. 

	\item All parsers should parse the '--help' and '-h' switch to print out usage information. 
	
	\item None of these parsers is allowed to make use of non-option and non-switch arguments because they are printed out by the core to allow a minimal user information on wrong used
arguments: The switches and options are parsed by the concerned parser and remaining elements (due to wrong placed spaces etc.) should be printed out as failures. 
\end{itemize}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Initialize-mode}
\label{InitializeMode}
The \GreenControl framework provides the {\em initialize-mode} which can be used by plugins and APIs to differ between elaboration and runtime without the need to derive from SystemC modules.

\GreenControl may be used immediately after construction (even before simulation runtime).% because we use immediate communication without events in the underlying \GreenBus framework.

To give the APIs the opportunity to check if the time is during initialize-mode there are callbacks:

If the APIs had to override the kernel callback functions to make their elaboration configuration
they would be forced to be SystemC modules. But we don't want them to be modules. So we have our own
interface (\lstinline|initialize_if|) which has to be implemented by each API which wants to use the
initialize-mode. %But even if an API does not need the initialize-mode each API has to implement this interface so that they can also be identified as interfaces for other issues (e.g. routing). 

All implementations of this interface are called by the only \lstinline|sc_module| in \GreenControl which is the so-called \lstinline|CallbackDispatcher|. The interface automatically registers itself with the Core (and the dispatcher), and unregisters as well when being destructed.
So simply deriving from this interface allows to use the functions and being called.

The interface contains the callback functions
\lstinline|start_initialize_mode| and \mbox{\lstinline|end_initialize_mode|.} Both functions are called by the Core while it processes the start\_of\_simulation SystemC callback. The first callback (\lstinline|start_initialize_mode|) may be used for initial configuration which was not yet done at construction time. The latter (\lstinline|end_initialize_mode|) shows the end of initialize-mode. From that point on the framework may be used in {\em runtime-mode}. With the help of these callbacks plugins and APIs can identify simulation runtime. Before and during the initialize-mode {\em no} events, notifies, time (even SC\_ZERO\_TIME) are allowed within the service communication. There are also optional calls \lstinline|gc_before_end_of_elaboration|,  \lstinline|gc_end_of_elaboration| and \lstinline|gc_end_of_simulation|.

An example how to use the initialize-mode callbacks can be seen in the \GreenConfig API implementation.



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{New Services}
\label{GCNewServices}

For adding Services to GreenControl there is an extension mechanism.

The base class \lstinline|gs::ctr::gc_service_ID_extension<my_service_ID>| is to derive service extensions from. 
Use the base class to identify the Plugin and API(s) against the \lstinline|gc_port|. The extension mechanism will automatically care for a simulation-wide unique ID\footnote{Note for debugging: This unique Service ID may vary when the number of used Services is changed or even if the include or instantiation order is changed!}.

Derive your service extension class in the following way:
\begin{lstlisting}
struct test_service_ID
: public gs::ctr::gc_service_ID_extension<test_service_ID>
{
  test_service_ID()
  : gs::ctr::gc_service_ID_extension<test_service_ID>("TEST_SERVICE") 
  { }
};
\end{lstlisting}

The extension constructor defines the debug and log string connected to the service ID.

This triggers proper service extension registration during C++ static
contruction time. There will be generated a unique Service ID.

\WarningSymbol{Note:} There are two different extension types: Service Extensions (these ones) and Transaction Extensions (see section \ref{sec:TransactionExtensions})!

\subsection{How to create new Service Plugins and User APIs}
See the example \textsf{new\_service\_example} for an example how to develop new Service Plugins and User APIs. Additionally you should have a look at the GC\_Logger which helps to analyse communication\footnote{The GC\_Logger currently does not support logging of transaction extensions} traffic over the Core.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Miscellaneous}
\label{GCMiscellaneous}

\subsection{SystemC 2.1}
When using \GreenControl with SystemC 2.1 there may be warnings like the one below. For OSCI SystemC 2.1v1 there is a workaround. Within other SystemC implementations these warnings can be presumably ignored. \newline
\begin{quote}
{\sffamily Warning: (W505) object already exists: fec. Latter declaration will be renamed to fec\_24 \newline
In file: ../../../../src/sysc/kernel/sc\_object.cpp:187} \newline
\end{quote}
